<template>
	<el-drawer
		title="车辆调度"
		v-model="dialogVisible"
		:destroy-on-close="true"
		class="vehicle-dispatch-drawer"
		:close-on-click-modal="false"
		size="95%"
		direction="rtl"
	>
		<template #header>
			<div class="drawer-header">
				<span>车辆调度</span>
			</div>
		</template>

		<div class="vehicle-dispatch-container">
			<div class="top-container">
				<!-- 地图区域 -->
				<div id="kupono-map" class="map-container">
					<div class="map-controls">
						<div class="filter-options">
							<el-checkbox v-model="filterOptions.showEmptyVehicles"
								>空闲车辆</el-checkbox
							>
							<el-checkbox v-model="filterOptions.showOccupiedVehicles"
								>在途车辆</el-checkbox
							>
							<el-checkbox v-model="filterOptions.all" checked
								>全部</el-checkbox
							>
						</div>
						<div class="distance-display">
							<span>里程: <strong>130km</strong></span>
							<span>耗时: <strong>2h07min</strong></span>
						</div>
					</div>
				</div>

				<!-- 使用新的调配面板组件 -->
				<dispatch-panel
					@dispatch-vehicle="handleDispatchVehicle"
					@quick-dispatch="handleQuickDispatch"
					@search="handleSearch"
				/>
			</div>
		</div>

		<!-- 已选车辆列表 -->
		<div class="selected-vehicles-container">
			<div class="table-header">
				<span>待调度车辆列表</span>
				<span>共 {{ vehicleTableData.length }} 条</span>
			</div>
			<el-table :data="vehicleTableData" border size="small" height="200">
				<el-table-column type="index" label="序号" width="50" align="center" />
				<el-table-column prop="plateNo" label="车牌号" min-width="100" />
				<el-table-column prop="driverName" label="司机名" width="80" />
				<el-table-column prop="driverPhone" label="联系电话" width="120" />
				<el-table-column prop="company" label="所属运营企业" min-width="150" />
				<el-table-column prop="status" label="车辆调度状态" width="100">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">
							{{ row.status }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column
					prop="planLoadingTime"
					label="计划装车时间"
					width="150"
				/>
				<el-table-column label="操作" width="80" align="center">
					<template #default="{ row }">
						<el-button type="danger" link @click="handleRemoveVehicle(row)">
							解除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<template #footer>
			<div class="drawer-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleSave">确认调度</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
import { ref, reactive, watch, onMounted, nextTick, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useMap } from '../useMap';
import DispatchPanel from './DispatchPanel.vue';

const mapManager = useMap();

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	defaultTimes: {
		type: Object,
		default: () => ({}),
	},
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const dialogVisible = ref(false);

// 筛选选项
const filterOptions = reactive({
	showEmptyVehicles: true,
	showOccupiedVehicles: true,
	all: true,
});

// 车辆表格数据
const vehicleTableData = ref([
	{
		plateNo: '川A00515D',
		driverName: '张三',
		driverPhone: '13500000000',
		company: 'XXXX运输有限公司',
		status: '已调',
		planLoadingTime: '2025-5-1 06:00:00',
	},
	{
		plateNo: '川A00565D',
		driverName: '王五',
		driverPhone: '13511111111',
		company: 'XXXX运输有限公司',
		status: '待确',
		planLoadingTime: '2025-5-3 10:30:27',
	},
]);

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	(val) => {
		dialogVisible.value = val;
		if (val) {
			nextTick(async () => {
				try {
					await mapManager.initMap();
					console.log('地图初始化完成');
				} catch (err) {
					console.error('地图初始化或创建元素失败:', err);
					console.error(err);
				}
			});
		}
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
});

onUnmounted(() => {
	mapManager.destroyMap();
});

// 获取状态类型
const getStatusType = (status) => {
	const statusMap = {
		已调: 'success',
		待确: 'warning',
		已完成: '',
		已取消: 'info',
	};
	return statusMap[status] || 'info';
};

// 处理搜索
const handleSearch = (keyword) => {
	if (keyword) {
		console.log('搜索车辆：', keyword);
		ElMessage.info(`正在搜索车牌为 ${keyword} 的车辆`);
	}
};

// 处理调派车辆
const handleDispatchVehicle = (plateNo) => {
	console.log('调派车辆：', plateNo);
	const vehicle = {
		plateNo,
		driverName:
			plateNo === '川A00515D'
				? '张三'
				: plateNo === '川A00565D'
					? '王五'
					: '李四',
		driverPhone: '13500000000',
		company: 'XXXX运输有限公司',
		status: '待确',
		planLoadingTime: props.defaultTimes.planLoadingTime || '2025-5-1 06:00:00',
		planArrivalTime: props.defaultTimes.planArrivalTime || '2025-5-1 08:00:00',
	};

	// 检查是否已经存在该车辆
	const exists = vehicleTableData.value.some(
		(item) => item.plateNo === plateNo,
	);
	if (exists) {
		ElMessage.warning('该车辆已在调度列表中');
		return;
	}

	// 添加到表格
	vehicleTableData.value.push(vehicle);
	ElMessage.success(`已调派车辆：${plateNo}`);
};

// 解除车辆
const handleRemoveVehicle = (row) => {
	ElMessageBox.confirm('确认要解除该车辆的调度吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			const index = vehicleTableData.value.findIndex(
				(item) => item.plateNo === row.plateNo,
			);
			if (index !== -1) {
				vehicleTableData.value.splice(index, 1);
				ElMessage.success('已解除车辆调度');
			}
		})
		.catch(() => {});
};

// 保存调度
const handleSave = () => {
	if (vehicleTableData.value.length === 0) {
		ElMessage.warning('请先选择要调度的车辆');
		return;
	}

	emit('confirm', vehicleTableData.value);
	dialogVisible.value = false;
	ElMessage.success('调度已确认');
};

// 处理一键派单
const handleQuickDispatch = () => {
	ElMessageBox.confirm('确认要一键派单给所有符合条件的车辆吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			// 这里添加一键派单的逻辑
			ElMessage.success('一键派单成功');
		})
		.catch(() => {});
};

onMounted(() => {
	// 初始化操作
});
</script>

<style lang="scss" scoped>
.vehicle-dispatch-drawer {
	:deep(.el-drawer__header) {
		margin-bottom: 0;
		padding: 15px 20px;
		border-bottom: 1px solid #e4e7ed;
		margin-right: 0;
	}

	:deep(.el-drawer__body) {
		padding: 0;
		height: calc(100% - 120px);
		overflow: hidden;
	}

	:deep(.el-drawer__footer) {
		padding: 10px 20px;
		border-top: 1px solid #e4e7ed;
	}
}

.vehicle-dispatch-container {
	display: flex;
	flex-direction: column;
	height: 100%;
}

.top-container {
	display: flex;
	flex: 1;
	min-height: 0;
	height: calc(100% - 250px);
}

.map-container {
	flex: 1;
	position: relative;
	background-color: #f0f2f5;
	min-height: 600px;
}

.map-controls {
	position: absolute;
	top: 20px;
	left: 20px;
	z-index: 100;
	width: 100%;
	pointer-events: none;

	.filter-options {
		display: inline-flex;
		gap: 15px;
		background: #fff;
		padding: 10px;
		border-radius: 4px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
		pointer-events: auto;
	}

	.distance-display {
		position: absolute;
		bottom: -60vh;
		left: 0;
		display: flex;
		gap: 15px;
		background: #fff;
		padding: 10px;
		border-radius: 4px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
		pointer-events: auto;

		strong {
			color: #409eff;
		}
	}
}

.selected-vehicles-container {
	height: 250px;
	border-top: 1px solid #e4e7ed;
	padding: 15px;
	background: #fff;

	.table-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10px;

		span:first-child {
			font-weight: bold;
		}

		span:last-child {
			color: #909399;
		}
	}

	:deep(.el-table) {
		height: calc(100% - 40px);
	}
}

.drawer-footer {
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

:deep(.custom-marker) {
	background-color: white;
	border: 2px solid #67c23a;
	border-radius: 6px;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
	padding: 3px 6px;
	color: #333;
	font-size: 12px;
	font-weight: bold;
	position: relative;

	&:before {
		content: '';
		position: absolute;
		bottom: -8px;
		left: 50%;
		transform: translateX(-50%);
		width: 0;
		height: 0;
		border-left: 6px solid transparent;
		border-right: 6px solid transparent;
		border-top: 6px solid #67c23a;
	}

	&.in-transit {
		border-color: #e6a23c;

		&:before {
			border-top-color: #e6a23c;
		}
	}
}

:deep(.map-type-switch) {
	position: absolute;
	right: 35px;
	bottom: 0px;
	z-index: 100;
	background: white;
	border-radius: 8px;
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
	padding: 4px;
	transition: opacity 0.3s ease;

	.map-type-options {
		display: flex;
		gap: 4px;
	}

	.map-type-option {
		position: relative;
		width: 80px;
		height: 60px;
		cursor: pointer;
		border-radius: 4px;
		transition: all 0.3s;
		overflow: hidden;

		.map-icon {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		&::after {
			content: attr(data-type);
			position: absolute;
			right: 4px;
			bottom: 4px;
			font-size: 12px;
			color: #666;
			background: rgba(255, 255, 255, 0.9);
			padding: 2px 6px;
			border-radius: 2px;
		}

		&:hover {
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
		}

		&.active {
			box-shadow: 0 0 0 2px #4a85f6;

			&::after {
				color: #4a85f6;
			}
		}
	}
}
</style>
